#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Copyright © 启明星辰 版权所有
# @Time    : 2023/11/2 17:04
# @Author  : 胡浩浩
# @File    : group_manage.py
# @IDE     : PyCharm
# @description : 分组管理
import json
import time

import jmespath
import requests
from pywebio.session import eval_js

from apps.commons.comms import close_pop, generate_uuid, replace_substring_in_list, IPADDRESS
from apps.commons.redis_tools import RedisClient
from apps.commons.yaml_tools import read_yml
from apps.commons.zentao_tools import ZenTaoTools

from pywebio.output import *
from pywebio.pin import put_input, pin, put_select, put_textarea, pin_update

from apps.commons.json_tools import read_json_file, write_json_file
from apps.src.menus import show_menus
import os

from config import APIPORT


# api_data_path = "data/"
# group_data_path = "data/group_data.json"
# count_data_path = "data/count_data.json"


def business_delete_group(data):
    # 先判断列表中的数据至少保留一条，否则不允许删除
    # 先删除当前的数据，再删除大盘里面的数据,紧接着删除对应的测试用例

    def delete_group():
        print("要删除的模块分组数据：", data)
        group_dict = {
            "product_name": data[0],
            "product_version": data[1],
            "swagger_name": data[2],
            "zentao_url": data[3],
        }
        result = requests.delete(f"http://{IPADDRESS}:{APIPORT}/groups", json=group_dict)
        print(result.json())
        toast(result.json()["message"])
        # todo 删除大盘里面的数据
        time.sleep(0.5)
        eval_js('window.location.reload();')

    popup('确认删除吗？', [
        put_row([
            put_text("将会删除关联的测试用例和对应的数据大盘数据")
        ]),
        put_row([
            put_text("  ")
        ]),
        put_row([
            None,
            put_button("确认", onclick=lambda: delete_group(), small=True),
            None,
            put_button("取消", onclick=lambda: close_popup(), color="dark", small=True)
        ], size="50%")
    ])


def update_mode_info(product_name):
    group_info = pin.group_info
    try:
        print(type(json.loads(group_info)))
        print("字典长度：", len(json.loads(group_info).keys()))
        # if not isinstance(json.loads(group_info), dict):
        #     toast("分组配置信息格式不正确，只能为json格式的数据", color="red")
        #     return
        if len(json.loads(group_info).keys()) == 0:
            toast("分组配置信息格式不正确，json格式不能为{}", color="red")
            return
        if len(json.loads(group_info).keys()) > 0:
            flag = False
            print("wzaizhix")
            dict(json.loads(group_info)).values()
            for v in dict(json.loads(group_info)).values():
                if not isinstance(v, list):
                    flag = True
                    break
                if len(v) == 0:
                    flag = True
                    break
            if flag:
                toast("分组配置信息格式不正确，配置的value不能为空，不能为非列表数据", color="red")
                return
    except Exception as e:
        print("出错了")
        toast("分组配置信息格式不正确，只能为json格式的数据", color="red")
        return
    print(group_info)
    print(product_name)
    group_dict = {
        "product_name": product_name,
        "group_info": group_info
    }
    result = requests.post(f"http://{IPADDRESS}:{APIPORT}/groups", json=group_dict)
    print(result.json())
    toast(result.json()["message"])
    time.sleep(1)
    eval_js('window.location.reload();')


def html_edit_model_info(data, product_name):
    return popup("维护模块信息",
                 [
                     put_textarea("group_info", rows=30, code={
                         'mode': "json",
                         'theme': 'darcula'
                     }, value=json.dumps(data, ensure_ascii=False, indent=4)),
                     put_row([
                         None,
                         put_button("保存", onclick=lambda: update_mode_info(product_name), small=True),
                         None,
                         put_button("关闭", onclick=lambda: close_popup(), color="dark", small=True)
                     ], size="70%")
                 ], size="large", closable=False
                 )


def business_data_list():
    result = requests.get(url=f"http://{IPADDRESS}:{APIPORT}/groups")
    print(result.json())
    list_data = result.json()
    list_data.reverse()
    for item in list_data:
        json_info = {}
        json_info.update(json.loads(item[1]))
        item[1] = "".join(["\n" + i for i in json.loads(item[1]).keys()])
        exec_code = f"""
item[1]=put_textarea('{generate_uuid()}',value=item[1],rows=1,readonly=True)
item.append(put_button("维护", onclick=lambda: html_edit_model_info({json_info},'{item[0]}'), small=True))
"""
        exec(exec_code)

    return len(list_data), list_data


def business_pages_data(total, data_list: list, current_page, search_keyword, table_header, page_size: int = 10):
    """
        第1页,start=0,end=10

        第2页strat=


    :return:
    """
    search_list = []
    print("search_keyword", search_keyword)
    if search_keyword != pin.group_search:
        search_keyword = pin.group_search
        if search_keyword:
            for f in data_list:
                if search_keyword in str(f[0]) or search_keyword in str(f[1]):
                    search_list.append(f)
            data_list = search_list
            total = len(search_list)
            print(f"{time.strftime('%Y-%m-%d %H:%M:%S：')}", total)
            print(f"{time.strftime('%Y-%m-%d %H:%M:%S：')}", len(search_list))
            current_page = 1
        else:
            total, data_list = business_data_list()
            print(f"{time.strftime('%Y-%m-%d %H:%M:%S：')}", total)
            print(f"{time.strftime('%Y-%m-%d %H:%M:%S：')}", data_list)

        print("search_keyword", pin.group_search)

    print("current_page", current_page)
    if current_page < 1:
        current_page = 1
        toast("已经第一页了", color="#00BFFF")
        return
    if current_page > int(len(data_list) / page_size) + 1:
        current_page = int(len(data_list) / page_size) + 1
        toast("已经最后一页了", color="#00BFFF")
        return

    start_index = (current_page - 1) * page_size
    end_index = start_index + page_size
    if end_index >= len(data_list):
        end_index = len(data_list)
    with use_scope("data_list", clear=True):
        put_tabs(
            [
                {
                    "title": "模块分组管理",
                    "content": [
                        put_button("新增", onclick=lambda: html_add_group(), small=True),
                        put_row(
                            [
                                put_text("变量名: "),
                                put_input(name="group_search", placeholder="请输入产品名称进行查询",
                                          value=search_keyword),
                                None,
                                put_button("搜索",
                                           onclick=lambda: business_pages_data(total, data_list, current_page,
                                                                               search_keyword, table_header),
                                           small=True),
                                put_button("重置",
                                           onclick=lambda: business_reset_data(1, total, data_list, table_header),
                                           small=True),
                            ], size="8% 50% 5% 6%"
                        ),
                        put_table(data_list[start_index:end_index],
                                  header=table_header),
                        put_row([
                            put_text(
                                f"      每页10条      当前第{current_page}/{int(total / 10) if total > 0 and total % 10 == 0 else int(total / 10) + 1}页     共{int(total / 10) if total > 0 and total % 10 == 0 else int(total / 10) + 1}页        总共{total}条"),
                            put_button("上一页", onclick=lambda: business_pages_data(total, data_list, current_page - 1,
                                                                                     search_keyword, table_header),
                                       small=True),
                            put_button("下一页", onclick=lambda: business_pages_data(total, data_list, current_page + 1,
                                                                                     search_keyword, table_header),
                                       small=True),
                        ], size="40% 6% 6%"
                        )

                    ]
                }
            ])


def business_reset_data(current_page, total, data_list, table_header):
    total, data_list = business_data_list()
    search_keyword = ""
    with use_scope("data_list", clear=True):
        put_tabs(
            [
                {
                    "title": "模块分组管理",
                    "content": [
                        put_button("新增", onclick=lambda: html_add_group(), small=True),
                        put_row(
                            [
                                put_text("变量名: "),
                                put_input(name="group_search", placeholder="请输入接口名称或者地址进行查询"),
                                None,
                                put_button("搜索",
                                           onclick=lambda: business_pages_data(total, data_list, current_page,
                                                                               search_keyword, table_header),
                                           small=True),
                                put_button("重置",
                                           onclick=lambda: business_reset_data(1, total, data_list, table_header),
                                           small=True),
                            ], size="8% 50% 5% 6%"
                        ),
                        put_table(data_list[:10], header=table_header),
                        put_row([
                            put_text(
                                f"      每页10条      当前第{current_page}/{int(total / 10) if total > 0 and total % 10 == 0 else int(total / 10) + 1}页     共{int(total / 10) if total > 0 and total % 10 == 0 else int(total / 10) + 1}页        总共{total}条"),
                            put_button("上一页",
                                       onclick=lambda: business_pages_data(total, data_list, current_page - 1,
                                                                           search_keyword, table_header),
                                       small=True),
                            put_button("下一页",
                                       onclick=lambda: business_pages_data(total, data_list, current_page + 1,
                                                                           search_keyword, table_header),
                                       small=True),
                        ], size="40% 6% 6%"
                        )

                    ]
                }
            ], scope="data_list"
        )


def business_save_group():
    # group_data_json = read_json_file(group_data_path)

    group_info = pin.group_info
    if not group_info:
        toast("分组配置信息不能为空", color="red")
        return
    product_name = pin.product_name
    try:
        print(type(json.loads(group_info)))
        print("字典长度：", len(json.loads(group_info).keys()))
        if not isinstance(json.loads(group_info), dict):
            toast("分组配置信息格式不正确，只能为json格式的数据,且不能为{}", color="red")
            return
        if len(json.loads(group_info).keys()) == 0:
            toast("分组配置信息格式不正确，json格式不能为{}", color="red")
            return
        if len(json.loads(group_info).keys()) > 0:
            flag = False
            print("wzaizhix")
            dict(json.loads(group_info)).values()
            for v in dict(json.loads(group_info)).values():
                if not isinstance(v, list):
                    flag = True
                    break
                if len(v) == 0:
                    flag = True
                    break
            if flag:
                toast("分组配置信息格式不正确，配置的value不能为空，不能为非列表数据", color="red")
                return
    except Exception as e:
        toast("分组配置信息格式不正确，只能为json格式的数据", color="red")
        return
    print(f"{time.strftime('%Y-%m-%d %H:%M:%S：')}", product_name)

    group_dict = {
        "product_name": product_name,
        "group_info": json.dumps(json.loads(group_info), ensure_ascii=False)
    }
    # print(group_dict)
    result = requests.post(f"http://{IPADDRESS}:{APIPORT}/groups", json=group_dict)
    print(result.json())
    toast(result.json()["message"])


def business_get_product_name():
    result = requests.get(f"http://{IPADDRESS}:{APIPORT}/api_doc")
    print(result.json())
    return [item[1] for item in result.json()]


def html_add_group():
    product_name = business_get_product_name()
    return popup('模块分组新增', [
        put_row([
            put_text("产品标识或版本"),
            put_select("product_name", product_name, help_text="请选择对应的产品"),
        ], size="20% 70%"),
        put_row([
            put_text("模块分组"),
            put_textarea("group_info", placeholder="json配置文件", rows=30, code={
                'mode': "json",
                'theme': 'darcula'
            }),
        ], size="20% 70%"),
        put_row([
            None,
            put_button("提交", onclick=lambda: business_save_group(), small=True),
            put_button('关闭', onclick=lambda: close_pop(), color="secondary", small=True)
        ], size="70% 15%"),

    ], size="large", closable=False)


def html_show_group():
    """
        模块分组
    """
    current_page = 1
    show_menus()
    total, data_list = business_data_list()
    search_keyword = ""
    table_header = [
        put_html('<h4 style="width:300px">产品标识或版本</h4>'),
        put_html('<h4 style="width:450px">模块分组信息</h4>'),
        put_html('<h4 style="width:330px">操作</h4>'),

    ]
    put_tabs(
        [
            {
                "title": "模块分组",
                "content": [
                    put_button("新增", onclick=lambda: html_add_group(), small=True),
                    put_row(
                        [
                            put_text("接口名称: "),
                            put_input(name="group_search", placeholder="请输入产品标识进行查询"),
                            None,
                            put_button("搜索",
                                       onclick=lambda: business_pages_data(total, data_list, current_page,
                                                                           search_keyword, table_header), small=True),
                            put_button("重置", onclick=lambda: business_reset_data(1, total, data_list, table_header),
                                       small=True)
                        ], size="8% 50% 5% 6%"
                    ),
                    put_table(data_list[0:10],
                              header=table_header),
                    put_row([
                        put_text(
                            f"      每页10条      当前第{current_page}/{int(total / 10) if total > 0 and total % 10 == 0 else int(total / 10) + 1}页     共{int(total / 10) if total > 0 and total % 10 == 0 else int(total / 10) + 1}页        总共{total}条"),
                        put_button("上一页",
                                   onclick=lambda: business_pages_data(total, data_list, current_page - 1,
                                                                       search_keyword, table_header),
                                   small=True),
                        put_button("下一页",
                                   onclick=lambda: business_pages_data(total, data_list, current_page + 1,
                                                                       search_keyword, table_header),
                                   small=True),
                    ], size="40% 6% 6%"
                    )

                ]
            }
        ], scope="data_list"
    )
